package src

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"simple-system/src/sql"

	"github.com/gin-gonic/gin"
	. "github.com/soekchl/myUtils"
)

type homeInfo struct {
	List []listInfo
}

type listInfo struct {
	Name    string       // 别名
	Path    string       // 关键字  或 数据库表
	Title   []titleInfo  // 表头
	SqlInfo *sql.SqlInfo // 数据库连接信息
}

type titleInfo struct {
	Name string // 别名
	Key  string // 保存key
}

func init() {
	buff := readFile(homeDataFilename)
	if len(buff) < 1 {
		os.MkdirAll(dataDir, 0644)
		outPutJson(home, homeDataFilename)
		Error("File is Empty ", homeDataFilename)
	}
	err := json.Unmarshal(buff, &home)
	if err != nil {
		Error(err)
		os.Exit(1)
	}
	for k, v := range home.List {
		homeMap[v.Path] = &home.List[k]
	}
}

// 主页
func Home(c *gin.Context) {
	str := `
<a href="/config" align="rigth"><b>设置</b></a>

<br>
%s
<hr>
%s
<br><input type="button" style="background: rgba(0,150,150,2)" onclick="newItem()" value=" 新 增 " >
`
	idx, info := getSelectPath(c)
	if info == nil {
		return
	}
	data, max := getList(info)
	str = fmt.Sprintf(str, getPathList(c), data)
	c.Writer.Write([]byte(fmt.Sprintf(homeHtml, str, showEditList(idx), info.Path, max)))
	c.Writer.WriteHeader(http.StatusOK)
}

func getPathList(c *gin.Context) (htmlStr string) {
	path, ok := c.GetQuery("path")
	if !ok || len(path) < 1 {
		path = home.List[0].Path
	}
	for _, v := range home.List {
		if path == v.Path {
			htmlStr += fmt.Sprintf(`<input type="button" style="font-weight: bold;background:yellow" onclick="getPath('%s')" value="%s"> `, v.Path, v.Name)
		} else {
			htmlStr += fmt.Sprintf(`<input type="button" onclick="getPath('%s')" value="%s"> `, v.Path, v.Name)
		}
	}

	return
}

func getSelectPath(c *gin.Context) (int, *listInfo) {
	path, ok := c.GetQuery("path")
	if !ok || len(path) < 1 {
		return 0, &home.List[0]
	}
	for k, v := range home.List {
		if v.Path == path {
			return k, &home.List[k]
		}
	}
	c.JSON(http.StatusBadRequest, gin.H{"msg": fmt.Sprintf("选择的 %s 不存在", path)})
	return 0, nil
}

// 回退
func FallBack(c *gin.Context) {
	if canFallBack() {
		os.Rename(fmt.Sprintf("%s_back", lastProcFileName), lastProcFileName)
		json.Unmarshal(readFile(homeDataFilename), &home) // NOTE 主页需要重新读取
		for k, v := range home.List {
			homeMap[v.Path] = &home.List[k]
		}
	}
	c.JSON(http.StatusOK, gin.H{"message": "ok"})
}

func canFallBack() bool {
	_, err := os.Stat(fmt.Sprintf("%s_back", lastProcFileName))
	return err == nil
}

func getSql(path string) sql.Sql {
	conn, ok := sqlMap[path]
	if ok {
		return conn
	}
	info, ok := homeMap[path]
	if !ok {
		panic("not found path=" + path)
	}
	conn, err := sql.Conn(info.SqlInfo)
	if err != nil {
		panic(err)
	}
	sqlMap[path] = conn
	return conn
}
